package binaryTree.LayerOrderTraversal;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Basic637 {
//二叉树的层平均值
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> resList = new ArrayList<List<Integer>>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if (root!=null){
            queue.offer(root);
        }
        while (!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> temp = new ArrayList<>();
            while (size>0){
                TreeNode node = queue.poll();
                size--;
                temp.add(node.val);

                if (node.left!=null){
                    queue.offer(node.left);
                }
                if (node.right!=null){
                    queue.offer(node.right);
                }
            }
            resList.add(temp);
        }
        return  resList;
    }
    public List<Double> averageOfLevels(TreeNode root) {
        List<List<Integer>> list = levelOrder(root);
        ArrayList<Double> doubles = new ArrayList<>();
        for (List<Integer>  a: list) {
            double temp=0.;
            for (int b: a) {
                temp+=(double) b/a.size();
            }
            doubles.add(temp);
        }
        return  doubles;
    }

    public List<Double> averageOfLevels1(TreeNode root) {
        List<Double> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();
        if (root == null) {
            return list;
        }
        que.offerLast(root);
        while (!que.isEmpty()) {
//            TreeNode peek = que.peekFirst();

            int levelSize = que.size();
            double levelSum = 0.0;
            for (int i = 0; i < levelSize; i++) {
                TreeNode poll = que.pollFirst();

                levelSum += poll.val;

                if (poll.left != null) {
                    que.addLast(poll.left);
                }
                if (poll.right != null) {
                    que.addLast(poll.right);
                }
            }
            list.add(levelSum / levelSize);
        }
        return list;
    }



    public static void main(String[] args) {

        TreeNode root= new TreeNode(5);
        TreeNode treeNode1 = new  TreeNode(3);
        TreeNode treeNode2=new TreeNode(1);
        TreeNode treeNode3 = new TreeNode(2);
        TreeNode treeNode4= new TreeNode(6);
        root.left=treeNode1;
        root.right=treeNode3;
        treeNode1.left=treeNode2;
        treeNode3.right=treeNode4;
        Basic637 basic637 = new Basic637();
        List<Double> doubles = basic637.averageOfLevels(root);
        for (Double a:
              doubles) {
            System.out.println(a);

        }


    }


}
